/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.prashant.sqlduniya.sqloutput;

import java.util.Collection;
import javax.swing.table.TableModel;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.prashant.sqlduniya.sqlmanager.DBConnectionManager;
import org.prashant.sqlduniya.sqlmanager.SQLQuery;
import org.prashant.sqlduniya.sqlmanager.SQLResult;
import org.prashant.sqlduniya.sqlmanager.TableBean;
import org.prashant.sqlduniya.sqlmanager.error.SQLDuniyaResultException;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.prashant.sqlduniya.sqloutput//SQLOutputView//EN",
autostore = false)
@TopComponent.Description(preferredID = "SQLOutputViewTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "output", openAtStartup = true)
@ActionID(category = "Window", id = "org.prashant.sqlduniya.sqloutput.SQLOutputViewTopComponent")
@ActionReference(path = "Menu/Window" /*
 * , position = 333
 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_SQLOutputViewAction",
preferredID = "SQLOutputViewTopComponent")
@Messages({
    "CTL_SQLOutputViewAction=SQLOutputView",
    "CTL_SQLOutputViewTopComponent=SQLOutputView Window",
    "HINT_SQLOutputViewTopComponent=This is a SQLOutputView window"
})
public final class SQLOutputViewTopComponent extends TopComponent {

    private static DBConnectionManager cm = null;
    private Lookup.Result<TableBean> tableNode = null;
    private TableSelectionListener tableSelectionListener = new TableSelectionListener();
    
    private Lookup.Result<SQLQuery> sqlQuery = null;
    private QueryRunListener queryRunListener = new QueryRunListener();
    
    public SQLOutputViewTopComponent() {
        initComponents();
        setName(Bundle.CTL_SQLOutputViewTopComponent());
        setToolTipText(Bundle.HINT_SQLOutputViewTopComponent());
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        tableViewPanel1 = new org.prashant.sqlduniya.sqloutput.TableViewPanel();
        infoViewPanel1 = new org.prashant.sqlduniya.sqloutput.InfoViewPanel();
        tableViewPanelResult = new org.prashant.sqlduniya.sqloutput.TableViewPanel();

        setLayout(new java.awt.BorderLayout());

        jTabbedPane1.addTab(org.openide.util.NbBundle.getMessage(SQLOutputViewTopComponent.class, "SQLOutputViewTopComponent.tableViewPanel1.TabConstraints.tabTitle"), tableViewPanel1); // NOI18N

        javax.swing.GroupLayout infoViewPanel1Layout = new javax.swing.GroupLayout(infoViewPanel1);
        infoViewPanel1.setLayout(infoViewPanel1Layout);
        infoViewPanel1Layout.setHorizontalGroup(
            infoViewPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 388, Short.MAX_VALUE)
        );
        infoViewPanel1Layout.setVerticalGroup(
            infoViewPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 259, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab(org.openide.util.NbBundle.getMessage(SQLOutputViewTopComponent.class, "SQLOutputViewTopComponent.infoViewPanel1.TabConstraints.tabTitle"), infoViewPanel1); // NOI18N
        jTabbedPane1.addTab(org.openide.util.NbBundle.getMessage(SQLOutputViewTopComponent.class, "SQLOutputViewTopComponent.tableViewPanelResult.TabConstraints.tabTitle"), tableViewPanelResult); // NOI18N

        add(jTabbedPane1, java.awt.BorderLayout.CENTER);
        jTabbedPane1.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(SQLOutputViewTopComponent.class, "SQLOutputViewTopComponent.jTabbedPane1.AccessibleContext.accessibleName")); // NOI18N
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.prashant.sqlduniya.sqloutput.InfoViewPanel infoViewPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private org.prashant.sqlduniya.sqloutput.TableViewPanel tableViewPanel1;
    private org.prashant.sqlduniya.sqloutput.TableViewPanel tableViewPanelResult;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        cm = Lookup.getDefault().lookup(DBConnectionManager.class);

        tableNode = Utilities.actionsGlobalContext().lookupResult(TableBean.class);
        tableNode.addLookupListener(tableSelectionListener);        
        
        sqlQuery = Utilities.actionsGlobalContext().lookupResult(SQLQuery.class);
        sqlQuery.addLookupListener(queryRunListener);       
        
    }

    @Override
    public void componentClosed() {
        cm = null;
        tableNode.removeLookupListener(tableSelectionListener);
        tableNode = null;
        
        sqlQuery.removeLookupListener(queryRunListener);
        sqlQuery = null;
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
    public void showTab(int index) {
        jTabbedPane1.setSelectedIndex(index);
    }

    private class TableSelectionListener implements LookupListener {

        @Override
        public void resultChanged(LookupEvent ev) {            
            Collection<? extends TableBean> tables = tableNode.allInstances();
            //selection of table is made so execute the below to fill data
            if (!tables.isEmpty()) {
                TableBean selectedTable = tables.iterator().next();

                try {
                    SQLResult sqlRs = cm.loadTable(selectedTable, 0, 10);
                    TableModel model = new TableNodeModel(sqlRs);
                    tableViewPanel1.getjXTableData().setModel(model);
                    showTab(0);
                } catch (SQLDuniyaResultException ex) {
                    NotifyDescriptor d = new NotifyDescriptor.Message(ex.getMessage(), NotifyDescriptor.WARNING_MESSAGE);
                    DialogDisplayer.getDefault().notify(d);
                }
            }

        }
    }
    
    private class QueryRunListener implements LookupListener {

        @Override
        public void resultChanged(LookupEvent ev) {            
            Collection<? extends SQLQuery> query = sqlQuery.allInstances();
            //selection of table is made so execute the below to fill data
            if (!query.isEmpty()) {
                SQLQuery toRunQuery = query.iterator().next();

                try {
                    SQLResult sqlRs = cm.loadResult(toRunQuery.getSql());
                    TableModel model = new TableNodeModel(sqlRs);
                    tableViewPanelResult.getjXTableData().setModel(model);
                    showTab(2);
                } catch (SQLDuniyaResultException ex) {
                    NotifyDescriptor d = new NotifyDescriptor.Message(ex.getMessage(), NotifyDescriptor.WARNING_MESSAGE);
                    DialogDisplayer.getDefault().notify(d);
                }
            }

        }
    }
}
